package com.hxx.mapper;

import com.hxx.domain.TUser;
import com.hxx.utils.DbManager;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.util.List;

public class UserMapperImpl implements UserMapper {
    Connection conn = DbManager.getInstance().getConn();
    //创建查询对象
    QueryRunner queryRunner = new QueryRunner();

    @Override
    public void save(TUser user) {
        try {
            queryRunner.update(conn,
                    "insert into t_user(username, sex, age) values(?, ?, ?)",
                    user.getUsername(), user.getSex(), user.getAge());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public TUser findById(int id) {
        try {
            return queryRunner.query(conn,
                    "select id, username, sex, age from t_user where id = ?",
                    new BeanHandler<>(TUser.class), id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void update(TUser user) {
        try {
            queryRunner.update(conn,
                    "update t_user set username = ?, sex = ?, age = ? where id = ?",
                    user.getUsername(), user.getSex(), user.getAge(), user.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void delete(int id) {
        try {
            queryRunner.update(conn,
                    "delete from t_user where id = ?",
                    id);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<TUser> findAll() {
        try {
            return queryRunner.query(conn,
                    "select id, username, sex, age from t_user",
                    new BeanListHandler<>(TUser.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<TUser> findAll(int page, int pageSize) {
        try {
            //分页查询
            return queryRunner.query(conn,
                    "select * from t_user limit ?,?",
                    new BeanListHandler<>(TUser.class),page,pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int rows() {
        try {
            // 使用ScalarHandler处理单行单列的结果（count(*)的结果）
            Long count = queryRunner.query(conn,
                    "select count(*) from t_user", new ScalarHandler<>());
            // 避免count为null的情况，转换为int返回
            return count != null ? count.intValue() : 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
















